<template>
  <div id="code-container" />
</template>

<script>
import { loginApi } from '@/api/api.js'

export default {
  name: 'LogByDing',
  data() {
    return {
      loading: true,
      appId: '',
      loginUrl: '',
      redirectUri: ''
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    async init() {
      await this._getDingTalkInfo()
      this._dingTalkLogin()
    },
    async _getDingTalkInfo() {
      await this.$request(loginApi.getDingTalkInfo).then((res) => {
        const data = res.data
        this.appId = data.appId
        this.loginUrl = data.loginUrl + encodeURIComponent('#/login')
        // this.loginUrl = 'https://oapi.dingtalk.com/connect/qrconnect?appid=dingoaupbsbpj7swwm7laz&response_type=code&scope=snsapi_login&state=dingtalk&redirect_uri=http://127.0.0.1:8080/' + encodeURIComponent('#/login')
        this.redirectUri = data.redirectUri + encodeURIComponent('#/login')
        // this.redirectUri = 'http://127.0.0.1:8080/' + encodeURIComponent('#/login')
      })
    },

    // 登录
    _dingTalkLogin() {
      const _this = this
      window.DDLogin({
        id: 'code-container',
        // goto这里需要对url整体做一个urlencode编码
        goto: encodeURIComponent(_this.loginUrl),
        style: 'border:none;background-color:#FFFFFF;',
        width: '100%',
        height: '300'
      })

      let handleMessage = function (event) {
        let origin = event.origin
        if (origin == 'https://login.dingtalk.com') {
          //判断是否来自ddLogin扫码事件。
          let loginTmpCode = event.data

          let url = 'https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=' + _this.appId + '&response_type=code&scope=snsapi_login&state=dingtalk&redirect_uri=' + _this.redirectUri + '&loginTmpCode=' + loginTmpCode + ''
          window.location.href = url
        }
      }
      if (typeof window.addEventListener != 'undefined') {
        window.addEventListener('message', handleMessage, false)
      } else if (typeof window.attachEvent != 'undefined') {
        window.attachEvent('onmessage', handleMessage)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.code-container {
  text-align: center;
  font-size: 12px;
}
</style>
